<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  .box {
    width: 500px;
    height: 500px;
    background-color: #ccc;
    color: #fff;
    text-align: center;
    font-size: 100px;
  }
</style>
</head>

<body>
  <div class="box"></div>


  <h3>总结</h3>
  <h5>防抖：</h5>
  <p>单位时间内，频繁触发事件，只执行最后一次，常用于搜索框输入、手机号、邮箱验证输入检测</p>
  <h5>节流：</h5>
  <p>单位事件内，频发触发使事件，只执行一次，常用于高频事件：如鼠标移动mousemove、页面尺寸缩放resize、滚动条滚动scroll等</p>
  <script src="./lodash.min.js"></script>
  <script>
    const box = document.querySelector(".box");
    let i = 1;

    function mouseMove() {
      box.innerHTML = i++;
    }
    // box.addEventListener("mousemove", mouseMove)
    // box.addEventListener("mousemove", _.throttle(mouseMove, 500))

    function throttle(fn, t) {
      let timer = null;
      return function () {
        if (!timer) {
          timer = setTimeout(function () {
            fn()
            // 清空定时器
            // clearInterval() ---> setTimeout中是无法删除定时器的，因为定时器还在运作，所以使用timer = null，而不是clearInteval()
            timer = null
          }, t)
        }
      }
    }
    box.addEventListener("mousemove", throttle(mouseMove, 500))
  </script>

</body>

</html>